import { authApi } from '../api/auth'
import { taskApi } from '../api/task'
import { topicApi } from '../api/topic'
import { userApi } from '../api/user'
import { $event, $storage } from '../utils'
import { getAccessToken, getServer, setAccessToken } from './mutations'
import { GlobalData } from './state'

export async function getUserTopics({ for_user, limit }: { for_user: number; limit: number }) {
  const id: any = GlobalData.logged ? GlobalData.logged.id : 0
  const expired_at = GlobalData.userTopics.expired_at
  const timestamp = new Date().valueOf()
  if (id && expired_at < timestamp) {
    const topics = await topicApi.getUserTopics({ for_user, limit })
    // eslint-disable-next-line require-atomic-updates
    GlobalData.userTopics = {
      // 设置10分钟的缓存时间
      expired_at: timestamp + 600000,
      topics,
    }
  }
  return Promise.resolve(GlobalData.userTopics.topics)
}

/**
 * 检查用户授权
 *
 * 授权后会返回 Promise.resolve(), 否则会抛出错误
 *
 * @param login 是否呼出授权页面
 */
/** 触发用户登录奖励 */
export function loginTask() {
  return $event.emit('after:login')
}
export async function checkAuth(login = true) {
  const token = getAccessToken()
  if (token) {
    loginTask()
    return Promise.resolve()
  }
  if (login) {
    $event.emit('login')
    return Promise.reject('登录授权检查未通过，呼出授权页面')
  }
  return Promise.reject('登录授权检查未通过')
}
export async function doVote(login = true) {
  $event.emit('vote', true)
  GlobalData.vote = true
  return Promise.reject('呼出投票页面')
}
/** 获取登录用户信息 */
export async function getDomoUser() {
  const user = await authApi.getCurrentUser()
  GlobalData.logged = user
  await $storage.set('logged', user, { sync: false })
  $event.emit('logged', user)
}

/** 获取用户信息
 */
export function getUser() {
  return wx.getStorageSync(`${getServer()}/logged`).data
}
/** 传入数组，更新用户数据 (仅环信聊天)*/
export async function getUsers(array: any[]) {
  const uids = array
    .map((r) => {
      if (r.username !== 'admin') {
        return GlobalData.imVersion.length > 0
          ? r.username.replace(GlobalData.imVersion, '')
          : r.username
      }
    })
    .filter((i) => i && i !== getUser().id)
  if (uids.length > 0) {
    const users = await userApi.getUser(uids)
    array = array.map((r) => {
      r.user = users.find((u) => `${GlobalData.imVersion}` + u.id == r.username)
      return r
    })
  }
  return array
}
/**
 * 根据 code 和微信返回加密的数据来登录
 *
 * @returns 是否已注册, 如果返回 `false` 则等待绑定手机号进行注册
 */
export async function authLogin(
  code: string,
  encryptResult: WechatMiniprogram.GetUserInfoSuccessCallbackResult,
) {
  // 获取用户openid
  const res = await authApi.getUserAccount({
    code,
    encryptedData: encryptResult.encryptedData,
    iv: encryptResult.iv,
    signature: encryptResult.signature,
    openid: '',
  })
  // getUserAccount返回的数据是 res值是 {"type":"logined","token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2hvdWRvbmcuZWNvYWMuY24vYXBpL3YyL3dlY2hhdC9taW5pLXByb2dyYW0iLCJpYXQiOjE3MjcyNDY5MzAsImV4cCI6MTcyODU0MjkzMCwibmJmIjoxNzI3MjQ2OTMwLCJqdGkiOiJrRVBubHlBZ1ZVZXlKd043Iiwic3ViIjo1NCwicHJ2IjoiNDhlNDUzODMxY2ViYTVlNTdhNDc1ZTY4NjQ5Y2ZkZWU2ZTk3ZDhkMiJ9.Z7BYfnQm-YPLZfUHDoPNVyE5exJODpTTKGShvhXGzRs","expires_in":21600,"openid":"ovNAk7TAhbJsNG8lFwi_iLzj3C1Q"}

  GlobalData.openId = res.openid
  console.log('openid is' + GlobalData.openId)
  if (res.type === 'alert') {
    wx.showModal({
      title: '错误',
      content: res.message,
    })
    throw new Error(res.message)
  } else if (res.type === 'logined') {
    setAccessToken(res.token, res.expires_in)
    // GlobalData = '微信用户'
    // $storage.remove('registerInfo')
    await getDomoUser()
    $event.emit('after:login')
    taskApi.getTasks()
    return true
  } else {
    $storage.set('registerInfo', res, { expires: 1440 })
    return false
  }
}

/** 获取任务列表 (需授权) */
export async function fetchTasks() {
  GlobalData.tasks = await taskApi.getTasks()
}

/** 获取通知，设置tabbar */
export async function getNotifications() {
  const { badges }: { badges: any } = await userApi.getNewsList()
  $event.emit('message:showMineDot', badges.following > 0)
  // badges.following
  //   ? wx.showTabBarRedDot({
  //     index: 4,
  //   })
  //   : wx.hideTabBarRedDot({
  //     index: 4,
  //   })

  const messageNum =
    badges.system +
    badges.comment +
    badges.like +
    badges.reward +
    badges.answer +
    badges.mall_selling_commodity +
    badges.selling_knowledge +
    (GlobalData.unReadMessageNum || 0)
  $event.emit('message:showMessageDot', messageNum > 0)
  return badges
  // messageNum > 0
  //   ? wx.showTabBarRedDot({
  //     index: 3,
  //   })
  //   : wx.hideTabBarRedDot({
  //     index: 3,
  //   })
}
